package com.wechatFriendExportTool.utils;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author JiXin
 * @date 2023/9/18 下午4:39
 */
public class FileUtil {

    /**
     * @Description: 读取指定文件夹下的指定类型的文件
     * @Author: JiXin
     * @Date: 2023/9/18 下午5:04
     **/
    public static List<String> loadFiles(String basePath,String fileType,List<String> lst){
        URL resource = FileUtil.class.getClassLoader().getResource(basePath);
        if (resource == null){
            return lst;
        }
        if ("jar".equals(resource.getProtocol())){
            //jar包读取
            loadFilesInJar(basePath, fileType, lst);
        }else {
            String path = resource.getFile();
            try {
                //防止空格被转换成%20
                path = URLDecoder.decode(path,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File file = new File(path);
            if (file.isDirectory()){
                //如果当前文件是文件夹 那么获取下面所有的文件
                String[] list = file.list();
                for (String s : list) {
                    loadFiles(basePath + "/" + s,fileType,lst);
                }
            }else if (file.isFile()){
                if (isEmpty(fileType) || basePath.endsWith("." + fileType)){
                    lst.add(basePath);
                }
            }
        }
        return lst;
    }

    private static boolean isEmpty(String fileType){
        return fileType == null || "".equals(fileType);
    }

    /**
     * @Description: 读取jar内的文件夹信息
     * @Author: JiXin
     * @Date: 2023/9/18 下午4:54
     **/
    public static List<String> loadFilesInJar(String basePat,String fileType,List<String> lst){
        try {
            ClassLoader classLoader = FileUtil.class.getClassLoader();
            URL url = classLoader.getResource(basePat);
            String urlStr = url.toString();
            //找到!/ 截断之前的字符串
            String jarPath = urlStr.substring(0, urlStr.indexOf("!/") + 2);
            URL jarURL = new URL(jarPath);
            JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection();
            JarFile jarFile = jarCon.getJarFile();
            Enumeration<JarEntry> jarEntrys = jarFile.entries();
            while (jarEntrys.hasMoreElements()) {
                JarEntry entry = jarEntrys.nextElement();
                // 简单的判断路径，如果想做到像Spring，Ant-Style格式的路径匹配需要用到正则
                String name = entry.getName();
                if (name.startsWith(basePat) && !name.equals(basePat)) {
                    if (entry.isDirectory()) {
                        //文件夹 迭代
                        loadFilesInJar(name, fileType, lst);
                    } else if (!lst.contains(name)) {
                        if (isEmpty(fileType) || name.endsWith("." + fileType)) {
                            lst.add(name);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return lst;
    }

    /**
     * @Description: 读取指定文件夹下的指定类型的文件
     * @Author: JiXin
     * @Date: 2023/9/18 下午5:06
     **/
    public static InputStream loadFiles(String basePath,String fileType){
        ClassLoader classLoader = FileUtil.class.getClassLoader();
        URL resource = classLoader.getResource(basePath);
        if (resource == null){
            return null;
        }
        if ("jar".equals(resource.getProtocol())){
            //jar包读取
            return loadFilesInJar(basePath,fileType);
        }else {
            String path = resource.getFile();
            try {
                //防止空格被转换成%20
                path = URLDecoder.decode(path, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File file = new File(path);
            if (file.isDirectory()){
                //如果当前文件是文件夹 那么获取下面所有的文件
                String[] list = file.list();
                for (String s : list) {
                    return loadFiles(basePath + "/" + s,fileType);
                }
            }else if (file.isFile()){
                if (isEmpty(fileType) || basePath.endsWith("." + fileType)){
                    return classLoader.getResourceAsStream(basePath);
                }
            }
        }
        return null;
    }

    /**
     * @Description: 读取jar内的指定文件的流
     * @Author: JiXin
     * @Date: 2023/9/18 下午5:12
     **/
    public static InputStream loadFilesInJar(String basePath,String fileType){
        InputStream resourceAsStream = null;
        try {
            ClassLoader classLoader = FileUtil.class.getClassLoader();
            URL url = classLoader.getResource(basePath);
            String urlStr = url.toString();
            // 找到!/ 截断之前的字符串
            String jarPath = urlStr.substring(0, urlStr.indexOf("!/") + 2);
            URL jarURL = new URL(jarPath);
            JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection();
            JarFile jarFile = jarCon.getJarFile();
            Enumeration<JarEntry> jarEntry = jarFile.entries();
            while (jarEntry.hasMoreElements()) {
                JarEntry entry = jarEntry.nextElement();
                //简单的判断路径，如果想做到像Spring，Ant-Style格式的路径匹配需要用到正则
                String name = entry.getName();
                if (name.startsWith(basePath) && !name.equals(basePath)){
                    if (entry.isDirectory()){
                        //文件夹 迭代
                        loadFilesInJar(name,fileType);
                    }else if (isEmpty(fileType) || name.endsWith("." + fileType)){
                        return classLoader.getResourceAsStream(name);
                    }
                }
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resourceAsStream;
    }
}